package cn.leancloud.leanstoragegettingstarted;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.SaveCallback;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
  private RecyclerView mRecyclerView;
  private MainRecyclerAdapter mRecyclerAdapter;
  private List<AVObject> mList = new ArrayList<>();

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //注销账户
    final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
      @Override
      public boolean onMenuItemClick(MenuItem item) {
        if (item.getItemId() == R.id.action_logout) {
          AVUser.getCurrentUser().logOut();
          startActivity(new Intent(MainActivity.this, LoginActivity.class));
          MainActivity.this.finish();
        }
        return false;
      }
    });
    //上传文件
    FloatingActionButton mUpload = (FloatingActionButton) findViewById(R.id.btn_upload);
    mUpload.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, -1);
      }
    });
    mRecyclerView = (RecyclerView) findViewById(R.id.list_main);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
    mRecyclerAdapter = new MainRecyclerAdapter(mList, MainActivity.this);
    mRecyclerView.setAdapter(mRecyclerAdapter);   //连接起来！！！
  }
  //onActivityResult函数响应了选择文件的操作
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {  //通过onActivityResult回调方法获取选择的文件Uri,从而实现文件路径及其信息的获取
    super.onActivityResult(requestCode, resultCode, data);
    String mFileName=null;
    if (requestCode == -1 && resultCode == RESULT_OK) {
      Uri fileUri = data.getData();  //得到uri，后面就是将uri转化成file的过程
      String[] filePathSplit = fileUri.getPath().split(":");
      String mFilePath=null;
      if (filePathSplit.length == 2) { //高版本系统内置文件选择器，只能从uri中得到相对路径，形式为：PRimary：文件相对路径
        String relativeFilePath = null;
        relativeFilePath = filePathSplit[1];
        mFilePath = Environment.getExternalStorageDirectory() + "/" + relativeFilePath;//getExternalStorageDirectory()方法可以获取内部存储器的路径。
      } else { //低版本系统文件选择器，可以直接从uri中得到绝对路径
        mFilePath = fileUri.getPath();
      }
      String[] folders = mFilePath.split("/");
      mFileName = folders[folders.length-1];
      //mFileNameTextView.setText(mFileName);
      Log.d("saved", "选择了文件:" + mFilePath);
    } else {
      Log.d("saved", "没有选择文件");
    }
    AVFile loadingFile = null;
    File file=new File("");
    try { loadingFile = AVFile.withFile(mFileName, file); } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    loadingFile.saveInBackground(new SaveCallback() {   //上传到服务器
      @Override
      public void done(AVException e) {
        if (e == null) {
          Log.d("saved", "文件上传成功！");
        } else {
          Log.d("saved", "文件上传失败! " + e.getMessage() + "|" + e.getCause());
        }
      }
    });
  }


  protected void onResume() {
    super.onResume();
    AVAnalytics.onResume(this);
    initData();
  }

  @Override
  protected void onPause() {
    super.onPause();
    AVAnalytics.onPause(this);
  }

  private void initData() {
    mList.clear();
    AVQuery<AVObject> avQuery = new AVQuery<>("Product");
    avQuery.orderByDescending("createdAt");
    avQuery.include("owner");
    avQuery.findInBackground(new FindCallback<AVObject>() {
      @Override
      public void done(List<AVObject> list, AVException e) {
        if (e == null) {
          mList.addAll(list);
          mRecyclerAdapter.notifyDataSetChanged();
        } else {
          e.printStackTrace();
        }
      }
    });
  }
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_logout) {
      return true;
    }

    return super.onOptionsItemSelected(item);
  }
}
